package com.gzu;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.IOException;

@WebFilter("/*") // 应用该过滤器到所有URL路径
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化时执行的操作（如果需要）
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取请求的URI
        String requestURI = httpRequest.getRequestURI();

        // 定义不需要登录即可访问的路径
        String[] excludePaths = {"/login.html", "/LoginServlet"};
        boolean isExcluded = false;

        for (String path : excludePaths) {
            if (requestURI.endsWith(path) || requestURI.startsWith(path)) {
                isExcluded = true;
                break;
            }
        }

        if (isExcluded || isUserLoggedIn(httpRequest)) {
            // 用户已登录或请求的是排除路径，继续处理请求
            chain.doFilter(request, response);
        } else {
            // 用户未登录，重定向到登录页面
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.html");
        }
    }

    @Override
    public void destroy() {
        // 过滤器销毁时执行的操作（如果需要）
    }

    /**
     * 检查用户是否已经登录
     */
    private boolean isUserLoggedIn(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        return session != null && session.getAttribute("user") != null;
    }
}